package com.tools.cleanmaster.utils;

import android.os.Bundle;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.Iterator;


public class JsonParser {
    private static final String TAG = "DxJsonParser";
    private static final boolean DEBUG = FeatureConfig.DEBUG_LOG;

    private int mResponseCode;
    private long mServerTime;

    public JSONObject parseResponse(String response) throws JSONException {
        JSONObject root = new JSONObject(response);
        parseHeader(root);
        return root.getJSONObject("response");
    }

    public JSONArray parseResponse2(String response) throws JSONException {
        JSONObject root = new JSONObject(response);
        parseHeader(root);
        return root.getJSONArray("response");
    }

    private void parseHeader(JSONObject root) throws JSONException {
        JSONObject header = root.getJSONObject("responseHeader");
        if (!header.isNull("errcode")) {
            mResponseCode = header.getInt("errcode");
        } else {
            mResponseCode = header.getInt("status"); // CMS response header
        }
        if (!header.isNull("time")) {
            // "time" may not exist in CMS response header
            mServerTime = header.getLong("time");
        }
    }

    public boolean isResponseOK() {
        return mResponseCode == 200;
    }

    public int getResponseCode() {
        return mResponseCode;
    }

    public long getServerTime() {
        return mServerTime;
    }

    public static boolean isResponseOK(String response) throws JSONException {
        JSONObject root = new JSONObject(response);
        return isResponseOK(root);
    }

    public static boolean isResponseOK(JSONObject root) throws JSONException {
        JsonParser parser = new JsonParser();
        parser.parseHeader(root);
        return parser.isResponseOK();
    }

    public static Bundle jsonToBundle(JSONObject json) throws JSONException {
        Bundle result = new Bundle();
        for (Iterator<?> it = json.keys(); it.hasNext(); ) {
            String key = (String) it.next();
            Object value = json.get(key);
            if (value instanceof String) {
                result.putString(key, (String) value);
            } else if (value instanceof Long) {
                result.putLong(key, (Long) value);
            } else if (value instanceof Integer) {
                result.putInt(key, (Integer) value);
            } else if (value instanceof Double) {
                result.putDouble(key, (Double) value);
            } else if (value instanceof Float) {
                result.putFloat(key, (Float) value);
            } else {
                LogHelper.w(TAG, "not supported value: " + value);
            }
        }
        if (DEBUG) {
            LogHelper.d(TAG, "result bundle: " + result.toString());
        }
        return result;
    }
}
